using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Client.Base;
using Client.Hotfix;
using Cysharp.Threading.Tasks;
using UnityEngine;

namespace Client.Hotfix
{
    [SSM(SSMWeight.UIService)]
    public class UISerivce : IAwake,IDestroy
    {
        private  ResourceService res;
        private readonly Dictionary<int, CUI> uiCache = new();
        public void Awake(params object[] args)
        {
            this.Log("[Service] - UIService is running...");
            res = Api.Instance.Get<ResourceService>();
        }

        public void Destroy()
        {
            foreach (var item in uiCache.Values)
            {
                item.Destroy();
            }
            uiCache.Clear();
        }


        public async UniTask<T> Show<T>(object arg = null) where T : CUI
        {
            int hashcode = typeof(T).GetHashCode();
            if (!uiCache.TryGetValue(hashcode, out var ui))
            {
                ui = Activator.CreateInstance(typeof(T)) as T;
                uiCache.Add(hashcode, ui);
            }

            if (ui.IsShow) return ui as T;

            if (!ui.HasEntity)
            {
                var clone = await res.LoadPrefabSync(ui.DefPrefab);
                ui.Awake(clone);
            }
            ui.Show(arg);
            return ui as T ;
        }

        public void Hide<T>() where T : CUI
        {
            int hashcode = typeof(T).GetHashCode();
            if (!uiCache.TryGetValue(hashcode, out var ui))
            {
                return;
            }
            if (!ui.IsShow) return;
            ui.Hide();
        }


        public T Get<T>()where T : CUI
        {
            int hashcode = typeof(T).GetHashCode();
            if (uiCache.TryGetValue(hashcode, out var ui))
            {
                return ui as T;
            }
            return null;
        }

        public void Release<T>() where T : CUI
        {
            int hashcode = typeof(T).GetHashCode();
            if (!uiCache.TryGetValue(hashcode, out var ui))
            {
                return;
            }
            ui.Destroy();
        }

    }
}

